package com.gitee.pifeng.monitoring.ui.business.web.controller;


import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.pifeng.monitoring.ui.business.web.annotation.OperateLog;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorEnv;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorGroup;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorEnvService;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorFeedService;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorGroupService;
import com.gitee.pifeng.monitoring.ui.business.web.vo.LayUiAdminResultVo;
import com.gitee.pifeng.monitoring.ui.business.web.vo.MonitorFeedVo;
import com.gitee.pifeng.monitoring.ui.business.web.vo.MonitorHttpVo;
import com.gitee.pifeng.monitoring.ui.constant.OperateTypeConstants;
import com.gitee.pifeng.monitoring.ui.constant.UiModuleConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hpsf.Thumbnail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/monitor-feed")
@Api(tags = "工单")
public class MonitorFeedController {

    /**
     * 监控环境服务类
     */
    @Autowired
    private IMonitorEnvService monitorEnvService;

    /**
     * 监控分组服务类
     */
    @Autowired
    private IMonitorGroupService monitorGroupService;
    @Autowired
    private IMonitorFeedService monitorFeedService;

    public static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    public static final String accessKeyId = "LTAI5tGvxXsT1trR8qr9vyZy";
    public static final String accessKeySecret = "usYOXgOMwoKbIqmTrSoJSVe03R4NPe";
    public static final String bucketName = "feedimages";
    @ApiOperation(value = "访问工单列表页面")
    @GetMapping("/list")
    public ModelAndView list(){
        ModelAndView mv = new ModelAndView("feed/feed");
        // 监控环境列表
        List<String> monitorEnvs = this.monitorEnvService.list().stream().map(MonitorEnv::getEnvName).collect(Collectors.toList());
        // 监控分组列表
        List<String> monitorGroups = this.monitorGroupService.list().stream().map(MonitorGroup::getGroupName).collect(Collectors.toList());
        mv.addObject("monitorEnvs", monitorEnvs);
        mv.addObject("monitorGroups", monitorGroups);
        return mv;
    }
    @ApiOperation(value = "获取工单列表")
    @GetMapping("/get-monitor-feed-list")
    @ResponseBody
    @OperateLog(operModule = UiModuleConstants.HTTP4SERVICE, operType = OperateTypeConstants.QUERY, operDesc = "获取工单列表")
    public LayUiAdminResultVo getMonitorFeedList(Long current, Long size,String feedNumber,String submitUser,String solveUser,Integer status){
        Page<MonitorFeedVo> page = this.monitorFeedService.getMonitorFeedList(current,size,feedNumber,submitUser,solveUser,status);
        return LayUiAdminResultVo.ok(page);
    }

    @ApiOperation(value = "访问新增工单页面")
    @GetMapping("/add-feed-form")
    public ModelAndView addFeedForm() {
        ModelAndView mv = new ModelAndView("feed/add-feed");
        return mv;
    }

    @RequestMapping(value="/uploadconimage",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadconimage(HttpServletRequest request,@RequestParam MultipartFile file) {
        Map<String,Object> mv=new HashMap<String, Object>();
        Map<String,String> mvv=new HashMap<String, String>();
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String rootPath = "D:\\IDEA\\ITTool\\phoenix\\phoenix-ui\\src\\main\\resources\\static\\feed";
//            String rootPath = request.getSession().getServletContext().getRealPath("classpath:/static/feed");
            System.out.println(rootPath);
            Calendar date = Calendar.getInstance(); //Calendar.getInstance()是获取一个Calendar对象并可以进行时间的计算，时区的指定
            String originalFile = file.getOriginalFilename(); //获得文件最初的名字
            String uuid = UUID.randomUUID().toString();    //UUID转化为String对象
            String newfilename=date.get(Calendar.YEAR)+""+(date.get(Calendar.MONTH)+1)+""+date.get(Calendar.DATE)+uuid.replace("-", "")+originalFile;
            //得到完整路径名
//            File newFile = new File(newfilename);
//            /*文件不存在就创建*/
//            if(!newFile.getParentFile().exists()){
//                newFile.getParentFile().mkdirs();
//            }

            File filePath = new File(rootPath + File.separator + newfilename);
            BufferedImage read = ImageIO.read(file.getInputStream());
            Thumbnails.of(read).scale(0.2f).toFile(rootPath+File.separator+"ceshi.jpg");
            FileUtils.copyInputStreamToFile(file.getInputStream(),filePath);
            PutObjectResult putObjectResult = oss.putObject(bucketName, newfilename, new File(rootPath + File.separator + "ceshi.jpg"));
            File file1 = new File(rootPath + File.separator + newfilename);
            file1.delete();
            mvv.put("src", "https://"+bucketName+"."+endpoint+"/"+newfilename);
            mvv.put("title", putObjectResult.getETag());
            mv.put("code", 0);
            mv.put("msg", "上传成功");
            System.out.println("上传成功");
            mv.put("data", mvv);

            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            mv.put("success", 1);
            return mv;
        }
    }
    @RequestMapping("/save_feed")
    public void saveFeed(@RequestParam(value = "content") String content){
        System.out.println(content);
    };
    @RequestMapping("/feed-detail")
    public ModelAndView feedDetail(){
        ModelAndView modelAndView = new ModelAndView("feed/feed-detail");
        MonitorFeedVo monitorFeedVo = new MonitorFeedVo();
        monitorFeedVo.setContent("12");
        modelAndView.addObject(monitorFeedVo);
        return modelAndView;
    }

}